﻿/*
   Open Intel 
   Copyright © 2011 – ISC. All Rights Reserved.
*/

using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.Threading;

namespace OI.Web.DataServices
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class SharingService
    {
        const int Retries = 3;


        [OperationContract]
        public void WriteState(Guid id, string state)
        {
            Func<string> act = () =>
            {
                using (var dc = new OIDataContext(Global.OIConnectionString))
                {
                    var newRow = new OI_Share {ID = id, State = state};
                    dc.OI_Shares.InsertOnSubmit(newRow);
                    dc.SubmitChanges();
                }
                return "";
            };
            TryWithRetry(act);
        }


        [OperationContract]
        public string ReadState(Guid id)
        {
            Func<string> act = () =>
            {
                using (var dc = new OIDataContext(Global.OIConnectionString))
                {
                    var rows = (from r in dc.OI_Shares
                                where r.ID == id
                                select r).FirstOrDefault();
                    if (rows != null)
                    {
                        return rows.State;
                    }
                }
                return "";
            };
            return TryWithRetry(act);
        }


        // tries an action several times before failing
        // necessary for back-ends such as SQL Azure
        private static string TryWithRetry(Func<string> act)
        {
            int rc = 0;
            string lastErr = null;

            while (rc < Retries)
            {
                try
                {
                    return act();
                }
                catch (Exception ex)
                {
                    rc++;
                    lastErr = "SharingService Failure: " + ex.Message;
                    Thread.Sleep(1000);
                }
            }
            return lastErr;
        }
    }
}
